import { promiseRequest } from "../../../utils/index";
import { imgBaseUrl } from "../../../utils/config";
var timeoutId;
Page({
  data: {
    wxQcodefileId: '',
    wxQcodefileIdLocal: '',
    rewardName:''
  },
  onLoad(options) {
    let actId = options.actId;
    //生成页面的小程序二维码,活动id做为参数
    this.generatorCode(actId);
  },
  onUnload() {
    if (timeoutId) {
      clearTimeout(timeoutId);
    }
  },
  createPicture() {
    let ctx = wx.createCanvasContext('picCanvas');
    let qrcode_width = 180, qrcode_height = 180, qrcode_x = 80, qrcode_y = 150;

    ctx.save()
    ctx.rect(0, 0, 343, 400)
    ctx.setFillStyle('#FFFFFF')
    ctx.fill();

    ctx.restore();
    ctx.setFontSize(20);
    ctx.fillText(this.data.rewardName, 55,55);
    ctx.fillText("推荐给你，亲测活动超实惠", 65,90);

    ctx.closePath();

    // 二维码
    ctx.save();
    ctx.beginPath();
    // ctx.arc(qrcode_width / 2 + qrcode_x, qrcode_height / 2 + qrcode_y, qrcode_width / 2, 0, Math.PI * 2, false);
    // ctx.clip();
    ctx.drawImage(this.data.wxQcodefileIdLocal, qrcode_x, qrcode_y, qrcode_width, qrcode_height);
    ctx.restore();

    // 生成并保存图片到相册
    ctx.draw(true, timeoutId=setTimeout(() => {
      wx.canvasToTempFilePath({
        x: 0,
        y: 0,
        width: 343,
        height: 400,
        destWidth: 343 * 3,
        destHeight: 400 * 3,
        fileType: 'jpg',
        canvasId: 'picCanvas',
        success: (res) => {
          console.log(res.tempFilePath)
          wx.hideLoading();
          wx.saveImageToPhotosAlbum({
            filePath: res.tempFilePath,
            success: (res) => {
              console.log(res);
              wx.showToast({
                title: '保存成功'
              });
            },
            fail: (error) => {
              console.log(error);
              wx.showToast({
                title: '报错图片失败',
                icon: 'none'
              });
            }
          })
        }
      })
    }, 1000));
  },
  saveImage() {
    wx.showLoading({title: '正在保存图片..'});
    wx.getImageInfo({
      src: this.data.wxQcodefileId,
      success: (res) => {
        this.setData({
          wxQcodefileIdLocal: res.path
        });
        this.createPicture();
      }
    });
  },
//生成小程序码
generatorCode(actId) {
  let requestObj = {
    url: '/wxa/actshare/generatorCode',
    method: 'post',
    dataobj: { actId: actId },
  };
  promiseRequest(requestObj).then((res) => {
    if (res.code == 200) {
      this.setData({
        wxQcodefileId: imgBaseUrl + "/" + res.data.wxQcodefileId,
        rewardName: res.data.rewardName
      });
    }
  }).catch((errMsg) => {
  });
},
})